package actions;


import java.util.HashMap;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import db.DBModel;

@WebServlet
public class UpdateUserAction extends Action{

	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response){		
		try{
			Map<String,String> errorMessages = new HashMap<String,String>();
			
			DBModel db = new DBModel();
			
			int userId = Integer.parseInt(request.getParameter("userId"));
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			String bio = request.getParameter("bio");

			if(db.emailExists(email, userId)){
				errorMessages.put("email", "Email '"+email+"' already exists!");
				request.setAttribute("errorMessages", errorMessages);
				return mapping.findForward("invalid");
			}
			else{
			
				//Decide whether to update with new password or not
				if(! (password==null || password.trim().isEmpty()) ){
					db.updateUser(email, password, bio, userId);
				}
				else{
					db.updateUser(email, bio, userId);
				}
				
				db.commit();
				
				if(request.isUserInRole("admin"))
				{
					if(!(request.getUserPrincipal().getName().toLowerCase().equals(db.getUserFromId(userId).getUsername().toLowerCase())))
					{
						//admin is editing someone's profiel:
						return mapping.findForward("adminsuccess");
					}
				}
				db.close();
				request.setAttribute("success", "User profile successfully updated!");
				return mapping.findForward("success");
			}
		}catch (Exception e){
			e.printStackTrace();
			request.setAttribute("error", e.toString());
			return mapping.findForward("fail");
		}	
	}
}
